<template>
  <div id="login">
    <div class="login-form">
      <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item>
          <img class="logo" src="../../assets/image/logo.png" />
          <div class="title">Pear Admin</div>
          <div class="desc">明 湖 区 最 具 影 响 力 的 设 计 规 范 之 一</div>
        </a-form-item>

        <a-form-item v-bind="validateInfos.account">
          <a-input placeholder="账 户" v-model:value="modelRef.account" />
        </a-form-item>
        <a-form-item v-bind="validateInfos.password">
          <a-input
            placeholder="密 码"
            v-model:value="modelRef.password"
            type="password"
          />
        </a-form-item>
        <a-form-item>
          <a-checkbox @change="onChange" v-model:checked="modelRef.remember">
            记住我
          </a-checkbox>
          <a class="login-form-forgot" href=""> 忘记密码 </a>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 24 }">
          <a-button style="width: 100%" type="primary" @click="onSubmit">
            登录
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>
<script>
import { reactive, computed } from "vue";
import { useForm } from "@ant-design-vue/use";
import { loginAPI } from "../../api/api";
import { message } from "ant-design-vue";
import { useRoute, useRouter } from "vue-router";
let Base64 = require("js-base64").Base64;
export default {
  methods: {
    onChange(e) {
      console.log(`checked = ${e.target.checked}`);
    },
  },
  setup() {
    const routes = useRouter().options.routes;
    const router = useRouter();
    /**
     * 写入cookie
     * name  :表示cookie的名称，比如token
     * value  :表示cookie的值
     * exdays  :表示cookie的有效时间
     */
    const setCookie = (name, value, exdays) => {
      var d = new Date();
      d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
      var expires = "expires=" + d.toGMTString();
      document.cookie = name + "=" + value + "; " + expires;
    };
    /**
     * 读取cookie
     * name  :表示cookie的名称，比如token
     */
    const getCookie = (name) => {
      let ret, m;
      if (typeof name === "string" && name !== "") {
        if (
          (m = String(document.cookie).match(
            new RegExp("(?:^| )" + name + "(?:(?:=([^;]*))|;|$)")
          ))
        ) {
          ret = m[1] ? decodeURIComponent(m[1]) : "";
        }
      }
      return ret;
    };
    /**
     * 储存表单信息
     */
    const setUserInfo = (res) => {
      setCookie("token", res.data.data.accessToken, 7);
      setCookie("refreshToken",res.headers['x-access-token'])
      //判断用户是否勾选记住密码，如果勾选，向cookie中储存登录信息，如果没有勾选，储存的信息为空
      if (modelRef.remember) {
        setCookie("account", modelRef.account, 7);
        // base64加密密码
        let passWord = Base64.encode(modelRef.password);
        setCookie("password", passWord);
      } else {
        setCookie("account", "");
        setCookie("password", "");
      }
    };
    // 数据初始化
    const modelRef = reactive({
      account: getCookie("account"),
      password: getCookie("password")==undefined?"":Base64.decode(getCookie("password")),
      remember: getCookie("account") == "" ? false : true,
    });
    // 表单域规则
    const rulesRef = reactive({
      account: [
        {
          required: true,
          message: "请输入用户名",
        },
      ],
      password: [
        {
          required: true,
          message: "请输入密码",
        },
      ],
      remember: [],
    });
    //校验
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    //提交表单
    const onSubmit = (e) => {
      e.preventDefault();      
      validate()
        .then((res) => {
          loginAPI(modelRef).then((res) => {
            if (res.data.succeeded) {
              message.success("登录成功！");
              //console.log("登录成功！");
              // 储存登录信息
              setUserInfo(res);
              router.push("/dashboard/console");
            } else {
              message.error(res.data.errors);
              setCookie("account", "");
              setCookie("password", "");
              setCookie("token", "");
              setCookie("refreshToken", "");
            }
          });
        })
        .catch((err) => {
          //console.log(validateInfos);
          console.log("error", err);
        });
    };
    const reset = () => {
      resetFields();
    };

    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 24 },
      validateInfos,
      reset,
      modelRef,
      onSubmit,
    };
  },
};
</script>
<style lang="scss">
#login {
  width: 100%;
  height: 100%;
  background: url(../../assets/image/background.svg);
  background-size: cover;
  .login-form {
    margin: auto;
    width: 350px;
    min-height: 20px;
    padding-top: 150px;
    .ant-input {
      border-radius: 4px;
      height: 45px;
      line-height: 45px;
    }
    .ant-btn {
      height: 45px;
      line-height: 45px;
    }
  }
  .logo {
    width: 60px !important;
    margin-top: 10px !important;
    margin-bottom: 10px !important;
    margin-left: 20px !important;
    border: none;
    background-color: transparent;
  }

  .title {
    font-size: 30px !important;
    font-weight: 700 !important;
    margin-left: 20px !important;
    width: 300px;
    display: inline-block !important;
    height: 60px !important;
    line-height: 60px !important;
    margin-top: 10px !important;
    position: absolute !important;
  }
  .login-form-forgot {
    float: right;
  }
  .desc {
    width: 100% !important;
    text-align: center !important;
    color: gray !important;
    height: 60px !important;
    line-height: 60px !important;
  }
}
</style>